import React, { useState } from 'react';
import { Button, Spin, message } from 'antd';
import { connect } from 'umi';
import { TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import { havePermissions } from './tool';
import { postQueryConfigStationPower, postSaveConfigStationPower } from './service';
import type { IProps, IApplyType, IDataSourceType } from './type';
import { IStationDataPowerConfigPermissions } from './type';
import { List, ApplyModal } from './components/index';
import styles from './index.less';

const StationDataPowerConfig = (props: IProps) => {
  const { buttonPermissions } = props;
  const [dataSource, setDataSource] = useState<IDataSourceType[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true); // 合约管理列表是否加载中；
  const [isError, setIsError] = useState<boolean>(false); // 合约管理列表是否报错态

  // 初始化获取数据
  const fetchData = async () => {
    setIsLoading(true);
    const res: any = await postQueryConfigStationPower({});
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setDataSource(res?.data || []);
      setIsError(false);
    } else {
      message.error(res?.message || '查询失败');
      setIsError(true);
    }
    setIsLoading(false);
  };

  React.useEffect(() => {
    fetchData();
  }, []);

  // 授权申请
  const handleApply = async () => {
    const resoult = havePermissions(
      IStationDataPowerConfigPermissions.STATIONDATAPOWERCONFIGBUTTTON,
      buttonPermissions,
    );
    if (resoult) {
      const result: any = await ApplyModal.show({
        onOk: async (data: IApplyType) => {
          const res: any = await postSaveConfigStationPower(data);
          if (res && res.statusCode === HttpCode.SUCCESS) {
            message.error(res?.data);
          } else {
            message.error(res?.message || '申请失败');
          }
          return res;
        },
      });
      if (result && result.index === 1 && result.statusCode === HttpCode.SUCCESS) {
        fetchData();
      }
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.main}>
        <div className={styles.header}>
          <div className={styles.title}>历史申请记录</div>
          <Button type="primary" className={styles.button} onClick={handleApply}>
            授权申请
          </Button>
        </div>
        <div className={styles.bottom}>
          {isLoading ? (
            <Spin className={styles.spin} />
          ) : isError ? (
            <TRDefault type={'error'} message={'系统异常'} />
          ) : dataSource?.length > 0 ? (
            <List dataSource={dataSource} />
          ) : (
            <TRDefault type={'emptysm'} message={'暂无数据'} />
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ stationDataPowerConfig, global }: any) => ({
  global,
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
  stationDataPowerConfig,
}))(StationDataPowerConfig);
